package tf2pickup.listeners;

import org.pircbotx.PircBotX;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
import org.pircbotx.hooks.events.NickChangeEvent;
import tf2pickup.Config;
import tf2pickup.Players;

/**
 * Handles nickname-changes in the channel. If the user whose nickname has 
 * changed was added to the pickup, the nickname-change will be applied to the 
 * pickup's player-list as well.
 * @author Philipp Preß
 */
public class OnNickChange extends ListenerAdapter<PircBotX> {

    private Players players;
    private Config cfg;

    /**
     * Creates a new listener that will check for nickname-changes in the
     * irc-channel.
     * @param players list of players added to the pickup.
     */
    public OnNickChange(Players players, Config cfg) {
        this.players = players;
        this.cfg = cfg;
    }

    /**
     * will apply the nickname-change from the irc to the players-list.
     * @param event the dispatched event.
     */
    @Override
    public void onNickChange(NickChangeEvent<PircBotX> event) {
        if (players.containsPlayer(event.getOldNick())) {
            //Adding player with new nickname but old PlayerProperties
            players.addPlayer(event.getNewNick(), players.getPlayerProperties(event.getOldNick()));
            //Removing player with old nickname
            players.removePlayer(event.getOldNick());
            //Refresh topic
            event.getBot().getListenerManager().dispatchEvent(
                    new MessageEvent<PircBotX>(event.getBot(),
                            event.getBot().getChannel(cfg.ircChannel),
                            event.getUser(), "!status"));
        }
    }
}
